﻿namespace MA.MembershipProvider
{
    using System;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Configuration;
    using System.Web.Configuration;
    using System.Web.Security;
    using System.Windows.Forms;

    public partial class frmAdminUsers : Form
    {

        public frmAdminUsers()
        {
            InitializeComponent();
        }

        private string NameApplicationValuer;

        public string NameApplication
        {
            get { return NameApplicationValuer; }
            set { NameApplicationValuer = value; }
        }

        private void frmAdminUsers_Load(object sender, EventArgs e)
        {
            NameApplication = Properties.Settings.Default.NombreAplicacion.ToString();

            if (string.IsNullOrWhiteSpace(NameApplication))
            {
                NameApplication = "/";
            }
            LoadUser();
        }

        private void dgvUsuarios_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            MembershipUserCollection Users = Membership.GetAllUsers();

            foreach (MembershipUser User in Users)
            {
                if (User.UserName == dgvUsuarios.Rows[e.RowIndex].Cells[0].FormattedValue.ToString())
                {
                    txtNombreLogin.Text = User.UserName;
                    txtEmail.Text = User.Email;
                    txtPreguntaSecreta.Text = User.PasswordQuestion;
                }
            }
        }

        private void LoadUser()
        {
            try
            {
                dgvUsuarios.Rows.Clear();

                Membership.Provider.ApplicationName = NameApplication;

                var collection = Membership.GetAllUsers();
                var bindingList = new BindingList<MembershipUser>();

                foreach (MembershipUser member in collection)
                {
                    bindingList.Add(member);
                }

                dgvUsuarios.DataSource = bindingList;
            }
            catch (MembershipCreateUserException ex)
            {
                MessageBox.Show(GetErrorMessage(ex.StatusCode));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public string GetErrorMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        private void btoAgregarUser_Click(object sender, EventArgs e)
        {
            MembershipCreateStatus Stado = new MembershipCreateStatus();
            try
            {
                if (!string.IsNullOrWhiteSpace(txtNombreLogin.Text) && !string.IsNullOrWhiteSpace(txtPassword.Text) && !string.IsNullOrWhiteSpace(txtPasswordConfirm.Text))
                {
                    if (txtPassword.Text == txtPasswordConfirm.Text)
                    {
                        MembershipUser User = Membership.CreateUser(txtNombreLogin.Text, txtPassword.Text, txtEmail.Text, txtPreguntaSecreta.Text, txtRespuesta.Text, true, out Stado);
                        if (User == null)
                        {
                            MessageBox.Show(Stado.ToString());
                        }
                        else
                        {
                            MessageBox.Show("El usuario: " + txtNombreLogin.Text + "Fue Creado Exitosamente");
                            txtNombreLogin.Text = string.Empty;
                            txtPassword.Text = string.Empty;
                            txtPasswordConfirm.Text = string.Empty;
                            txtEmail.Text = string.Empty;
                            txtPreguntaSecreta.Text = string.Empty;
                            txtRespuesta.Text = string.Empty;
                        }

                        LoadUser();
                        dgvUsuarios.Refresh();
                    }
                    else
                    {
                        MessageBox.Show("El Password no coincide");
                    }
                }
                else
                {
                    MessageBox.Show("No pudimos dectectar el Nombre Login");
                }

            }
            catch (MembershipCreateUserException ex)
            {
                MessageBox.Show(GetErrorMessage(ex.StatusCode));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btoQuitarUser_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(txtNombreLogin.Text))
                {
                    if (Membership.DeleteUser(txtNombreLogin.Text, true))
                    {
                        txtNombreLogin.Text = string.Empty;
                        txtPreguntaSecreta.Text = string.Empty;
                        txtEmail.Text = string.Empty;
                        LoadUser();
                        dgvUsuarios.Refresh();
                        MessageBox.Show("El usuario y los datos del mismo fueron borrados exitosamente!");
                    }
                }
                else
                {
                    MessageBox.Show("No hay usuarios seleccionado para eliminar");
                }
            }
            catch (MembershipCreateUserException ex)
            {
                MessageBox.Show(GetErrorMessage(ex.StatusCode));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private NameValueCollection GetNameValueCollectionSection(string section, string filePath)
        {
            string file = filePath;
            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            NameValueCollection nameValueColl = new NameValueCollection();

            System.Configuration.ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = file;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            string xml = config.GetSection(section).SectionInformation.GetRawXml();
            xDoc.LoadXml(xml);

            System.Xml.XmlNode xList = xDoc.ChildNodes[0];
            foreach (System.Xml.XmlNode xNodo in xList)
            {
                nameValueColl.Add(xNodo.Attributes[0].Value, xNodo.Attributes[1].Value);
            }

            return nameValueColl;
        }

        private void btoModificarUser_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(txtNombreLogin.Text) || !string.IsNullOrWhiteSpace(txtEmail.Text))
                {
                    MembershipUserCollection Users = Membership.GetAllUsers();
                    MembershipUser User;

                    foreach (MembershipUser item in Users)
                    {
                        if (item.UserName == txtNombreLogin.Text)
                        {
                            item.Email = txtEmail.Text;
                            User = item;
                            Membership.UpdateUser(User);
                            LoadUser();
                            dgvUsuarios.Refresh();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Detectamos un error, puede ser que no exista el usuario seleccionado, que el campo mail este vacío. Cabe destacar que solo se puede modificar el Mail de un usuario por el momento.");
                }
            }
            catch (MembershipCreateUserException ex)
            {
                MessageBox.Show(GetErrorMessage(ex.StatusCode));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cboxResetPassword_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboxResetPassword.Checked)
                {
                    if (!string.IsNullOrWhiteSpace(txtNombreLogin.Text))
                    {
                        MembershipUserCollection Users = Membership.GetAllUsers();
                        
                        foreach (MembershipUser item in Users)
                        {
                            if (item.UserName == txtNombreLogin.Text)
                            {
                                txtResetPassword.Text = item.ResetPassword();
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("No encontramos al usuario seleccionado.");
                    }
                }
            }
            catch (MembershipCreateUserException ex)
            {
                MessageBox.Show(GetErrorMessage(ex.StatusCode));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
